<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库连接测试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .test-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .test-button {
            background: #409eff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        .test-button:hover {
            background: #66b1ff;
        }
        .result {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            white-space: pre-wrap;
        }
        .success {
            background: #f0f9ff;
            border: 1px solid #67c23a;
            color: #67c23a;
        }
        .error {
            background: #fef0f0;
            border: 1px solid #f56c6c;
            color: #f56c6c;
        }
        .info {
            background: #f4f4f5;
            border: 1px solid #909399;
            color: #606266;
        }
        .warning {
            background: #fdf6ec;
            border: 1px solid #e6a23c;
            color: #e6a23c;
        }
    </style>
</head>
<body>
    <h1>🔧 数据库连接问题诊断工具</h1>
    
    <div class="test-container">
        <h2>📊 问题分析</h2>
        <p>从错误信息看，登录失败的原因包括：</p>
        <ul>
            <li><strong>400 Bad Request</strong>: 请求参数问题</li>
            <li><strong>500 Internal Server Error</strong>: "Unable to commit against JDBC Connection" - 数据库连接问题</li>
        </ul>
    </div>

    <div class="test-container">
        <h2>🔍 后端API测试</h2>
        <button class="test-button" onclick="testLoginAPI()">测试登录API</button>
        <button class="test-button" onclick="testRolesAPI()">测试角色API</button>
        <button class="test-button" onclick="testUsersAPI()">测试用户API</button>
        <div id="apiResult" class="result info">点击按钮测试后端API...</div>
    </div>

    <div class="test-container">
        <h2>🗄️ 数据库状态检查</h2>
        <button class="test-button" onclick="checkDatabaseStatus()">检查数据库状态</button>
        <button class="test-button" onclick="testDatabaseConnection()">测试数据库连接</button>
        <div id="dbResult" class="result info">点击按钮检查数据库状态...</div>
    </div>

    <div class="test-container">
        <h2>🚀 解决方案</h2>
        <div class="warning">
            <h3>方案1: 检查MySQL服务</h3>
            <p>1. 打开服务管理器 (services.msc)</p>
            <p>2. 查找MySQL服务</p>
            <p>3. 确保服务状态为"正在运行"</p>
        </div>
        
        <div class="warning">
            <h3>方案2: 初始化数据库</h3>
            <p>1. 打开命令提示符</p>
            <p>2. 运行: <code>mysql -u root -p20020508 feedback_system &lt; back-end/database/unified_database.sql</code></p>
            <p>3. 或者手动执行SQL脚本</p>
        </div>
        
        <div class="warning">
            <h3>方案3: 检查数据库配置</h3>
            <p>1. 确认MySQL服务运行在3306端口</p>
            <p>2. 确认用户名: root, 密码: 20020508</p>
            <p>3. 确认数据库名: feedback_system</p>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:9090/api';
        
        function updateResult(elementId, content, type = 'info') {
            const element = document.getElementById(elementId);
            element.textContent = content;
            element.className = `result ${type}`;
        }

        async function testLoginAPI() {
            try {
                const loginData = {
                    username: 'admin',
                    password: 'admin123'
                };
                
                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(loginData)
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    updateResult('apiResult', 
                        `✅ 登录API测试成功\n` +
                        `状态码: ${response.status}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2)}`, 
                        'success'
                    );
                } else {
                    updateResult('apiResult', 
                        `❌ 登录API测试失败\n` +
                        `状态码: ${response.status}\n` +
                        `错误信息: ${data.message || '未知错误'}\n` +
                        `完整响应: ${JSON.stringify(data, null, 2)}`, 
                        'error'
                    );
                }
            } catch (error) {
                updateResult('apiResult', 
                    `❌ 登录API测试失败\n` +
                    `错误信息: ${error.message}\n` +
                    `可能原因: 后端服务未启动或网络连接问题`, 
                    'error'
                );
            }
        }

        async function testRolesAPI() {
            try {
                const response = await fetch(`${API_BASE_URL}/auth/roles`);
                const data = await response.json();
                
                if (response.ok) {
                    updateResult('apiResult', 
                        `✅ 角色API测试成功\n` +
                        `状态码: ${response.status}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2)}`, 
                        'success'
                    );
                } else {
                    updateResult('apiResult', 
                        `❌ 角色API测试失败\n` +
                        `状态码: ${response.status}\n` +
                        `错误信息: ${data.message || '未知错误'}`, 
                        'error'
                    );
                }
            } catch (error) {
                updateResult('apiResult', 
                    `❌ 角色API测试失败\n` +
                    `错误信息: ${error.message}`, 
                    'error'
                );
            }
        }

        async function testUsersAPI() {
            try {
                const response = await fetch(`${API_BASE_URL}/auth/users-simple`);
                const data = await response.json();
                
                if (response.ok) {
                    updateResult('apiResult', 
                        `✅ 用户API测试成功\n` +
                        `状态码: ${response.status}\n` +
                        `用户数量: ${data.data ? data.data.length : 0}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2)}`, 
                        'success'
                    );
                } else {
                    updateResult('apiResult', 
                        `❌ 用户API测试失败\n` +
                        `状态码: ${response.status}\n` +
                        `错误信息: ${data.message || '未知错误'}`, 
                        'error'
                    );
                }
            } catch (error) {
                updateResult('apiResult', 
                    `❌ 用户API测试失败\n` +
                    `错误信息: ${error.message}`, 
                    'error'
                );
            }
        }

        async function checkDatabaseStatus() {
            try {
                // 尝试获取用户列表来检查数据库连接
                const response = await fetch(`${API_BASE_URL}/auth/users-simple`);
                const data = await response.json();
                
                if (response.ok && data.data && data.data.length > 0) {
                    updateResult('dbResult', 
                        `✅ 数据库连接正常\n` +
                        `用户数量: ${data.data.length}\n` +
                        `测试用户: ${data.data.map(u => u.username).join(', ')}`, 
                        'success'
                    );
                } else {
                    updateResult('dbResult', 
                        `⚠️ 数据库连接可能有问题\n` +
                        `状态码: ${response.status}\n` +
                        `响应: ${JSON.stringify(data, null, 2)}`, 
                        'warning'
                    );
                }
            } catch (error) {
                updateResult('dbResult', 
                    `❌ 数据库连接失败\n` +
                    `错误信息: ${error.message}\n` +
                    `可能原因: MySQL服务未启动或数据库未初始化`, 
                    'error'
                );
            }
        }

        async function testDatabaseConnection() {
            try {
                // 测试多个API端点
                const endpoints = [
                    { name: '角色API', url: '/auth/roles' },
                    { name: '用户API', url: '/auth/users-simple' },
                    { name: '登录API', url: '/auth/login', method: 'POST', body: { username: 'admin', password: 'admin123' } }
                ];
                
                let results = [];
                
                for (const endpoint of endpoints) {
                    try {
                        const options = {
                            method: endpoint.method || 'GET',
                            headers: { 'Content-Type': 'application/json' }
                        };
                        
                        if (endpoint.body) {
                            options.body = JSON.stringify(endpoint.body);
                        }
                        
                        const response = await fetch(`${API_BASE_URL}${endpoint.url}`, options);
                        const data = await response.json();
                        
                        results.push(`${endpoint.name}: ${response.ok ? '✅ 成功' : '❌ 失败'} (${response.status})`);
                    } catch (error) {
                        results.push(`${endpoint.name}: ❌ 错误 (${error.message})`);
                    }
                }
                
                updateResult('dbResult', 
                    `🔍 数据库连接测试结果:\n${results.join('\n')}`, 
                    'info'
                );
            } catch (error) {
                updateResult('dbResult', 
                    `❌ 数据库连接测试失败\n` +
                    `错误信息: ${error.message}`, 
                    'error'
                );
            }
        }

        // 页面加载时自动检查
        window.onload = function() {
            checkDatabaseStatus();
        };
    </script>
</body>
</html>
